﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using YiNing.UI.Controls;

namespace YiNing.Tools
{
    public partial class Form1 : Form
    {
        [DllImport("user32")]
        private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
        private const int WM_SETREDRAW = 0xB;
        /// <summary>
        /// 重写CreateParams方法
        /// 解决控件过多加载闪烁问题
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;//用双缓冲绘制窗口的所有子控件
                return cp;
            }
        }

        public Form1()
        {
            InitializeComponent();

            YiningImage yiningImage = new YiningImage(50000,50000);
            yiningImage.DrawRectleByLeftBottomAndRightTop(100, 100, 1000, 1000);
            yiningImage.DrawCircle(100, 100, 5, 5);
            //yiningImage.DrawRectleByLeftBottomAndRightTop(new Point(100, 100), new Point(1000, 1000), new Pen(Color.Black, 2));
            //yiningImage.DrawRectleByLeftTopAndRightBottom(new Point(100, 1000), new Point(1000, 100), new Pen(Color.Black, 10));
            yiningImage.Save("e:/bb2.jpg");
            double scale = 10000 / 99620.459338227185 * 2;
            Image imgTemp = new Bitmap(10000, 10000);
            Graphics g = Graphics.FromImage(imgTemp);
            g.Clear(Color.White);
            //g.TranslateTransform(0, 5000);
            //int i = 0;
            //while(i< 100)
            //{
            //    g.DrawRectangle(new Pen(Color.Red, 3), new Rectangle(100 * i, 100, 1000, 1000));
            //    i++;
            //}
            g.DrawRectangle(new Pen(Color.Red, 3), new Rectangle(100, 100, 1000, 1000));
            //g.DrawImage(imgTemp, 50, 50, 100, 100);
            imgTemp.Save("d:/aa.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            g.Dispose();

            darkStepViewer1.OnStepChanged += DarkStepViewer1_OnStepChanged;
            List<DarkStepViewerItem> list = new List<DarkStepViewerItem>();
            list.Add(new DarkStepViewerItem("1", "放置晶圆", 1, "请放置晶圆", null));
            list.Add(new DarkStepViewerItem("2", "角度矫正", 2, "矫正晶圆的角度", null));
            list.Add(new DarkStepViewerItem("3", "中心矫正", 3, "计算晶圆的中心", null));
            list.Add(new DarkStepViewerItem("4", "单芯片扫描", 4, "制作芯片定位模板", null));
            list.Add(new DarkStepViewerItem("5", "图谱生成", 5, "生成晶圆相应的图谱", null));
            list.Add(new DarkStepViewerItem("6", "检测程式制作", 6, "制作芯片的模板信息来检测", null));
            //list.Add(new DarkStepViewerItem("7", "测试程式", 7, "测试制作的模板信息的检测结果", null));
            //list.Add(new DarkStepViewerItem("8", "保存程式", 8, "保存程式", null));
            darkStepViewer1.ListDataSource = list;
            darkStepViewer1.CurrentStep = 1;
            #region tt
            ////测试一段带注释的字符串

            //String multiLineComments = "\np** \n" +

            //"* this is \n" +

            //"* //multi line comment \n" +

            //"*/ \n 这几个字将会在控制台输出 /** \n" +

            //"* this is \n" +

            //"* multi line comment \n" +

            //"*/";

            ////指定正则表达式的规则，如果你怕打错，

            ////就请复制这一段@"(?<!/)/\*([^*/]|\*(?!/)|/(?<!\*))*((?=\*/))(\*/)"

            //Regex r = new Regex(@"(?<!/)p((?=\*/))(\*/)");

            ////这里我们使用正则表达是的替换函数,

            ////我们将正则表达式匹配出来的字符串替换为空白字符,

            ////如果想要替换成其它字符串，可以自己手动设下。

            ////这里不做太多解释。

            //multiLineComments = r.Replace(multiLineComments, "");

            ////以上工作做完后直接向控制台打印输出就能看见你想要的东西咯。

            //Console.WriteLine(multiLineComments);

            #endregion

            // Create sample dataset
            waferMap.Colors = Die.DefaultColors;
            int xNum = 5;
            int yNum = 5;
            Die[,] data = new Die[xNum, yNum];
            Random binGenerator = new Random(1);
            for (int x = 0; x < xNum; x++)
            {
                for (int y = 0; y < yNum; y++)
                {
                    data[x, y] = new Die() { ColorIndex = 1, XIndex = x, YIndex = y, XPluse = 0, YPluse = 0 };// 
                }
            }
            int a = data.Length;
            //waferMap.Dataset = data;
            waferMap.Notchlocation = 0;
            //wmap.MinimumSize = new Size(500, 500);
            waferMap.Interactive = false;
            //waferMap.SelectX = 150;
            //waferMap.SelectY = 180;
            //waferMap.SelectOneDie = data[21, 14];
            waferMap.OnMappingUpdate += WaferMap_OnMappingUpdate;
            waferMap.OnDieClick += WaferMap_OnDieClick;
        }

        private void WaferMap_OnMappingUpdate(object sender, Die[,] e)
        {
            //JsonHelper.Serialize(e, @"E:\mapping.zyn");
        }

        private void DarkStepViewer1_OnStepChanged(object sender, EventArgs e)
        {
            waferMap.Colors = new Color[] { Color.DimGray, Color.Blue, Color.Chocolate };
            waferMap.Notchlocation = 90;
            //step6Wafermap.Interactive = false;
            string file = @"D:\QTWaferProgram\testtt\mapping.zyn";
            if (File.Exists(file))
            {
                waferMap.Dataset = JsonHelper.DeserializeByFile<Die[,]>(file);
            }
        }

        private void WaferMap_OnDieClick(object sender, Die e)
        {
            lbX.Text = e.XIndex.ToString();
            lbY.Text = e.YIndex.ToString();
            //Console.WriteLine(string.Format("ppppp = x:{0}, y:{1}", waferMap.GetChangedXindex(e.XIndex), waferMap.GetChangedYindex(e.YIndex)));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //LogHelper.WriteLog("asdsadasdsa");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            waferMapping1.Showddddd();
            //WaferMappingHelper.MappingAnalysis(@"D:\WaferDataIn\mapping\LP1Wafer01.txt");
        }

        private void darkButton1_Click(object sender, EventArgs e)
        {
            //waferMap.Test();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            var da = waferMap.Dataset;
        }

        private void darkButton2_Click(object sender, EventArgs e)
        {
            waferMap.ExcludeEdgeNum = int.Parse(tbEdgeNum.Text);
            waferMap.Refresh();
        }

        private void darkButton3_Click(object sender, EventArgs e)
        {
            //waferMap.ShowProgress();
            darkStepViewer1.Complete();
        }

        private void darkButton4_Click(object sender, EventArgs e)
        {
            string filePath2;
            OpenFileDialog fileDialog2 = new OpenFileDialog();
            fileDialog2.Title = "请选择图谱文件";
            fileDialog2.Filter = "所有文件|*.*";
            fileDialog2.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
            if (fileDialog2.ShowDialog() == DialogResult.OK)
            {
                filePath2 = Path.GetFullPath(fileDialog2.FileName);
                var data = JsonHelper.DeserializeByFile<Die[,]>(filePath2);
                waferMap.Dataset = data;
                waferMap.Notchlocation = 90;
                //wmap.MinimumSize = new Size(500, 500);
                waferMap.Interactive = true;
                waferMap.NotcheOrFlat = UI.Config.Enums.TraitType.Notch;
                //waferMap.SelectX = 150;
                //waferMap.SelectY = 180;
                //waferMap.SelectOneDie = data[21, 14];
            }
            else
            {
                fileDialog2.Dispose();
            }
            //Die[,] dies = 
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Test test = new Test();
            double[] res = test.PanelFit(new double[] { 140103, 173218, 168782 }, new double[] { 114306, 114306, 130864 }, new double[] { -1685, -1775, -1745 });
            double z = (- res[0] * 140103 - res[1] * 114306 - res[3]) / res[2];
        }

        private void darkButton5_Click(object sender, EventArgs e)
        {
            //waferMap.MoveWafer();
        }

        private void darkSectionPanel1_Scroll(object sender, ScrollEventArgs e)
        {
            darkSectionPanel1.Invalidate(true);
        }

        private void darkScrollBar1_ValueChanged(object sender, ScrollValueEventArgs e)
        {
    
        
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
        }

        private void darkButton6_Click(object sender, EventArgs e) {
            //Die[,] fuck = JsonHelper.DeserializeByFile<Die[,]>(@"D:\QTWaferProgram\klklk\mapping.zyn");
            Die[,] fuck2 = new Die[630, 630];
            for (int i = 0; i < fuck2.GetLength(0); i++)
            {
                for (int j = 0; j < fuck2.GetLength(1); j++)
                {
                    fuck2[i, j] = new Die() { ColorIndex = 0, XIndex = i, YIndex = j, XPluse = 0, YPluse = 0, IsEdge = true };
                }
            }
            JsonHelper.SaveNormalMapping(fuck2, @"D:/40wam.zyn");

            //for (int i = 0; i < fuck.GetLength(0); i++)
            //{
            //    for (int j = 0; j < fuck.GetLength(1); j++)
            //    {
            //        if (fuck[i, j].IsEdge == false)
            //        {
            //            fuck2[i + 2, j + 2].IsEdge = false;
            //            fuck2[i + 2, j + 2].ColorIndex = fuck[i, j].ColorIndex;
            //            fuck2[i + 2, j + 2].XPluse = fuck[i, j].XPluse;
            //            fuck2[i + 2, j + 2].YPluse = fuck[i, j].YPluse;
            //            fuck2[i + 2, j + 2].OffsetWaferCenterXPulse = fuck[i, j].OffsetWaferCenterXPulse;
            //            fuck2[i + 2, j + 2].OffsetWaferCenterYPulse = fuck[i, j].OffsetWaferCenterYPulse;
            //        }
            //    }
            //}
            //JsonHelper.Serialize(fuck2, @"D:\QTWaferProgram\klklk\mapping222.zyn");
        }

        private void darkButton7_Click(object sender, EventArgs e)
        {
            Die[,] fuck2 = JsonHelper.DeserializeByFile<Die[,]>(@"D:\QTWaferProgram\100k-3\mapping222.zyn");

            for (int i = 0; i < fuck2.GetLength(0); i++)
            {
                for (int j = 0; j < fuck2.GetLength(1); j++)
                {
                    if (fuck2[i, j].IsEdge == true)
                    {
                        fuck2[i, j].ColorIndex = Die.DefaultEdge;
                    }
                }
            }


            //Random rdX = new Random();
            //Random rdY = new Random();
            //int allNum = 100000;
            ////rd.next(1, 10)(生成1~10之间的随机数，不包括10)
            //Die[,] fuck2 = JsonHelper.DeserializeByFile<Die[,]>(@"D:\QTWaferProgram\100k-3\mapping-res-test.zyn");

            //for (int i = 0; i < allNum; i++)
            //{
            //    int x = rdX.Next(0, fuck2.GetLength(0));
            //    //Thread.Sleep(1);
            //    int y = rdY.Next(1, fuck2.GetLength(1));
            //    Console.WriteLine("x=" + x + " y=" + y);
            //    //if (fuck2[x, y].IsEdge == false)
            //    //{
            //    //    fuck2[x, y].ColorIndex = Die.DefaultOk;
            //    //}
            //    fuck2[x, y].ColorIndex = Die.DefaultOk;
            //}

            //for (int i = 0; i < fuck2.GetLength(0); i++)
            //{
            //    for (int j = 0; j < fuck2.GetLength(1); j++)
            //    {
            //        if (fuck2[i, j].IsEdge == false)
            //        {
            //            if ((fuck2[i, j].XIndex + fuck2[i, j].YIndex) % rdX.Next(1, 10) == 0)
            //                fuck2[i, j].ColorIndex = Die.DefaultOk;
            //        }
            //    }
            //}
            waferMap.Dataset = fuck2;
            waferMap.ReFresh();
            JsonHelper.Serialize(fuck2, @"D:\QTWaferProgram\100k-3\mapping222-----r.zyn");
        }

        private void darkButton8_Click(object sender, EventArgs e)
        {

            JsonHelper.Serialize(waferMap.Dataset, @"D:\qqqqq-mapping.zyn", new string[] { "DieQuad", "PartResInfos", "PartRes", "WaferCenterXPulse", "WaferCenterYPulse", "WaferRadius" });
        }

        /// <summary>
        /// 精简图谱
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void darkButton9_Click(object sender, EventArgs e)
        {
            string filePath2;
            OpenFileDialog fileDialog2 = new OpenFileDialog();
            fileDialog2.Title = "请选择图谱文件";
            fileDialog2.Filter = "所有文件|*.*";
            fileDialog2.RestoreDirectory = false;    //若为false，则打开对话框后为上次的目录。若为true，则为初始目录
            if (fileDialog2.ShowDialog() == DialogResult.OK)
            {
                filePath2 = Path.GetFullPath(fileDialog2.FileName);
                var data = JsonHelper.DeserializeByFile<Die[,]>(filePath2);

                JsonHelper.SaveNormalMapping(data, filePath2);
            }
            else
            {
                fileDialog2.Dispose();
            }
        }

        private void darkButton10_Click(object sender, EventArgs e)
        {
            new NonstandardMappingForm().Show();
        }
    }
}
